package com.jacob.androidframe.util;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.FontMetrics;
import android.graphics.Paint.Style;
import android.util.TypedValue;

/**
 * 使用图片排版
 * 
 * @author GuoJiale
 * 
 */
public class DrawTextUtil {
	private Context context = null;
	private int width = 0;
	private int hight = 0;
	private Bitmap bm = null;
	private Paint mPaint;
	private FontMetrics fm;
	private float baseline;

	public Bitmap getBitmap() {
		return bm;
	}

	public DrawTextUtil(Context c, int w, int marginDp) {
		context = c;

		baseline = 0.0f;

		mPaint = new Paint();
		mPaint.setAntiAlias(true);
		mPaint.setColor(Color.DKGRAY);
		// mPaint.setColor(Color.parseColor("#DCDCDC"));
		mPaint.setStyle(Style.STROKE);

		this.width = w - DensityUtil.dip2px(c, 30);
	}

	/*
	 * Color.BLACK：黑色。
	 * 
	 * Color.BLUE：蓝色。
	 * 
	 * Color.CYAN：青绿色。
	 * 
	 * Color.DKGRAY：灰黑色。
	 * 
	 * Color.YELLOW：黄色。
	 * 
	 * Color.GRAY：灰色。
	 * 
	 * Color.GREEN：绿色。
	 * 
	 * Color.LTGRAY：浅灰色。
	 * 
	 * Color.MAGENTA：红紫色。
	 * 
	 * Color.RED：红色。
	 * 
	 * Color.TRANSPARENT：透明。
	 * 
	 * Color.WHITE：白色。
	 */

	public int getPicHight(String txt, int txtSize) {
		mPaint.setTextSize(getRawSize(TypedValue.COMPLEX_UNIT_DIP, txtSize));
		fm = mPaint.getFontMetrics();
		// 由于系统基于字体的底部来绘制文本，所有需要加上字体的高度。
		baseline = fm.descent - fm.ascent;
		//bug，当字体为一行时，显示不全
		// 行数据
		// 获取总高度
		hight = (int) (getRowCount(txt, mPaint) * (baseline + fm.leading));

		return hight;
	}

	public Bitmap drawText(String txt, int txtSize) {
		mPaint.setTextSize(getRawSize(TypedValue.COMPLEX_UNIT_DIP, txtSize));
		fm = mPaint.getFontMetrics();
		// 由于系统基于字体的底部来绘制文本，所有需要加上字体的高度。
		baseline = fm.descent - fm.ascent;
		float x = 0;
		float y = baseline;
		// 去一个汉字的宽度
		float one = getStringWidth(mPaint, "我");
		float lineWidth = 0;
		// 行数据
		String lineText = "";
		char[] texts = txt.toCharArray();
		boolean isEnter = false;
		// 获取总高度
		int currentRowCount = getRowCount(txt, mPaint);
		hight = (int) (currentRowCount * (baseline + fm.leading));
		//bug 当行数不足一时，显示不全  @大熊
		if (currentRowCount == 1) {
			hight +=10;
		}
		bm = Bitmap.createBitmap(width, hight, Config.ARGB_4444);

		Canvas canvas = new Canvas(bm);
		canvas.drawColor(Color.TRANSPARENT);

		for (int i = 0; i < texts.length; i++) {
			float charWidth = getStringWidth(mPaint, texts[i] + "");
			lineWidth += charWidth;
			lineText += texts[i];

			if (texts[i] == '\n') {
				isEnter = true;
			}
			if (lineWidth + one >= width || lineWidth >= width || isEnter
					|| i == texts.length - 1) {
				float disWidth = width - lineWidth;
				float aver = 0;
				// 有分隔符并且非最后一行
				if (!isEnter && !(i == texts.length - 1))
					aver = disWidth / lineText.length();
				for (int k = 0; k < lineText.length(); k++) {
					canvas.drawText(lineText.toCharArray()[k] + "", x, y,
							mPaint);
					x = x
							+ aver
							+ getStringWidth(mPaint, lineText.toCharArray()[k]
									+ "");
				}
				x = 0;
				lineWidth = 0;
				lineText = "";
				y += baseline + fm.leading;
				// Log.i("当前高度：", "y=" + y);
				isEnter = false;
			}
		}
		canvas.save(Canvas.ALL_SAVE_FLAG);
		canvas.restore();
		return bm;
	}

	private int getStringWidth(Paint paint, String str) {
		int iRet = 0;
		if (str != null && str.length() > 0) {
			int len = str.length();
			float[] widths = new float[len];
			paint.getTextWidths(str, widths);
			for (int j = 0; j < len; j++) {
				iRet += (int) Math.ceil(widths[j]);
			}
		}
		return iRet;
	}
	
	
	

	private int getRowCount(String content, Paint p) {
		float textWidth = p.measureText(content);
		int lines = 1; // 计算行数
		float lineWidth = 0;
		char[] texts = content.toCharArray();
		boolean isEnter = false;
		float one = getStringWidth(p, "我");

		if (textWidth <= width) {
			return lines;
		}

		for (int i = 0; i < texts.length; i++) {
			float charWidth = getStringWidth(p, texts[i] + "");
			lineWidth += charWidth;

			if (texts[i] == '\n') {
				isEnter = true;
			}
			if (lineWidth + one >= width || lineWidth >= width || isEnter
					|| i == texts.length - 1) {
				lineWidth = 0;
				lines++;
				isEnter = false;
			}
		}

		return lines;
	}

	/**
	 * 获取指定单位对应的原始大小（根据设备信息） px,dip,sp -> px
	 * 
	 * Paint.setTextSize()单位为px
	 * 
	 * 代码摘自：TextView.setTextSize()
	 * 
	 * @param unit
	 *            TypedValue.COMPLEX_UNIT_*
	 * @param size
	 * @return
	 */
	private float getRawSize(int unit, float size) {
		Context c = this.context;
		Resources r;

		if (c == null)
			r = Resources.getSystem();
		else
			r = c.getResources();

		return TypedValue.applyDimension(unit, size, r.getDisplayMetrics());
	}
}
